﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LoginManager
{
    private static LoginManager instance = new LoginManager();
    public static LoginManager Instance => instance;
    //本地用户数据
    public LoginData loginData;
    //模拟数据库的用户数据
    public UserData userData;
    //模拟数据库的服务器数据
    public ServerData serverData;
    private LoginManager() 
    {
        loginData = JsonManager.LoadData<LoginData>("LoginData");
        userData = JsonManager.LoadData<UserData>("UserData");
        serverData = JsonManager.LoadData<ServerData>("ServerData");
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <returns>是否登录成功</returns>
    public bool Login(string username, string password)
    {
        foreach (var item in userData.users)
        {
            if (item.username == username && item.password == password)
            {
                return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 保存登录数据
    /// </summary>
    public void SaveLoginData()
    {
        JsonManager.SaveData(loginData, "LoginData");
    }

    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <returns>是否注册成功</returns>
    public bool Register(string username, string password)
    {
        foreach (var item in userData.users)
        {
            if (item.username == username)
            {
                return false;
            }
        }
        userData.users.Add(new User(username,password));
        JsonManager.SaveData(userData, "UserData", false);
        return true;
    }

    /// <summary>
    /// 根据id获取Server(服务器)数据
    /// </summary>
    /// <param name="id">服务器id</param>
    /// <returns>Server(服务器数据)</returns>
    public Server QueryServerById(int id)
    {
        if (serverData.servers.ContainsKey(id.ToString()))
        {
            return serverData.servers[id.ToString()];
        }
        return serverData.servers.ContainsKey("1") ? serverData.servers["1"] : null;
    }

    /// <summary>
    /// 根据id范围获取服务器列表数组集合
    /// </summary>
    /// <param name="start">起始id</param>
    /// <param name="end">结束id</param>
    /// <returns>服务器列表数组集合</returns>
    public List<Server> QueryServersById(int start, int end)
    {
        if (end - start <= 0)
        {
            return null; 
        }
        List<Server> servers = new List<Server>();
        for (int i = start; i <= end; i++)
        {
            servers.Add(serverData.servers[i.ToString()]);
        }
        return servers;
    }
}
